package com.interview.javabase.algorithm.链表;

/**
 * 剑指 Offer 24. 反转链表
 * https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
 * @author zhangshguang
 * @date 2020/09/21
 */
public class 反转单链表 {

    public static void main(String[] args) {
        ListNode head = new ListNode(5);
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(1);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode listNode = reverseList(head);
        System.out.println(listNode.val);

    }

    /**
     * 头插法
     *
     * @param head
     * @return
     */
    public static ListNode reverseList(ListNode head) {

        if (head == null|| head.next == null){
            return head;
        }

        ListNode newListNode = reverseList1(head.next);
        head.next.next = head;
        head.next = null;

        return newListNode;
    }


    /**
     * 头插法
     *
     * @param head
     * @return
     */
    public static ListNode reverseList1(ListNode head) {

        if (head == null|| head.next == null){
            return head;
        }

        ListNode newListNode = null;

        while (head != null){
            ListNode temp = head.next;
            head.next = newListNode;
            newListNode = head;
            head = temp;
        }

        return newListNode;
    }
}
